#!/bin/bash

set -e

CONFIG_FILE=docker/local-config/docker-compose.yml
DOCKER_FILE=docker/local-config/Dockerfile
PULL_CMD="docker-compose -f $CONFIG_FILE pull"
UP_CMD="docker-compose up --build"

function rmContainers() {
  docker-compose -f $CONFIG_FILE rm -fv $SERVICE_NAME || true
}

CONTAINERS=(monitor zeebe)

for i in "${!CONTAINERS[@]}"
do
   SERVICE_NAME=${CONTAINERS[$i]} rmContainers
done

# extracting latest hazelcast exporter version
HAZELCAST_VERSION=$(sed -n 's/\(<hazelcast.exporter.version>\)\([a-z0-9.-]\+\)\(<\/hazelcast.exporter.version>\)/\2/p' pom.xml | awk '$1=$1{print}')

# replacing the hazelcadt version in the dockerfile
sed -i "s/HAZELCAST_EXPORTER_VERSION=.*/HAZELCAST_EXPORTER_VERSION=$HAZELCAST_VERSION/" $DOCKER_FILE
echo "Use hazelcast exporter version $HAZELCAST_VERSION"

$PULL_CMD

echo "Building project"
mvn clean install

echo "Building docker"
# docker run -it --rm --name maven-zeebe-simple-monitor -v "$(pwd)":/usr/src/zeebe-simple-monitor -w /usr/src/zeebe-simple-monitor maven:3.3-jdk-8 mvn clean install
docker build -t camunda/zeebe-simple-monitor:latest -f app/Dockerfile app
echo "Done"

cd docker/local-config/
echo "starting containers"
$UP_CMD

cd ../..
